<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/10
 * Time: 0:56
 */
namespace app\http\middleware;

use Naixiaoxin\ThinkWechat\Facade;
use think\facade\Log;
use think\facade\Session;
use think\facade\Hook;

class Wechat {
    public function handle($request, \Closure $next)
    {
        $officialAccount = Facade::officialAccount();
        if ($request->param('url')) {
            $officialAccount->oauth->setRedirectUrl($request->param('url'));
        }
        $session_key = 'wechat_oauth_user_default';
        $session     = Session::get($session_key);
        $scopes = ['snsapi_base'];
        if (!$session) {
            if ($request->get('code')) {
                $session = $officialAccount->oauth->user();
                Session::set($session_key, $session);
                Hook::listen('wechat_oauth', [
                    'user'   => $session,
                    'is_new' => true,
                ]);
                //跳转到登录
                Log::info($this->getTargetUrl($request));
                return redirect($this->getTargetUrl($request));
            }
            $url = $officialAccount->oauth->scopes($scopes)->redirect()->getTargetUrl();
            return redirect($url);
        }
        Hook::listen('wechat_oauth', [
            'user'   => $session,
            'is_new' => false,
        ]);
        return $next($request);
    }

    protected function getTargetUrl($request)
    {
        $param = $request->get();
        if (isset($param['code'])) {
            unset($param['code']);
        }
        if (isset($param['state'])) {
            unset($param['state']);
        }
        return $request->baseUrl() . (empty($param) ? '' : '?' . http_build_query($param));
    }
}